#include "Button.h"
#include "ReportError.h"
#include "Screen.h"
#include "TextureManager.h"
#include "Factory.h"

Button::Button()
{
	m_isPressed = false; 
	m_isOver = false; 

	m_SDLmouseCoord.X, m_SDLmouseCoord.Y = 0;
	m_OGLmouseCoord.X, m_OGLmouseCoord.Y = 0;
	m_dimensions.X, m_dimensions.Y = 0;
	m_maxPos.X, m_maxPos.Y = 0;
}

Button::~Button()
{
	//TheEventPoller::Instance()->RemoveHandler(this);
}

void Button::Draw()
{
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	TheTextureManager::Instance()->DrawTexture(m_texPath);

	glBegin(GL_QUADS);
		//counter clockwise winding 
		glTexCoord2f(0.0f, 1.0f); //coord for points
		glVertex3f((m_pos.X - 1.0f), (m_pos.Y - 1.0f), 0); //UVs

		glTexCoord2f(1.0f, 1.0f); //coord for points
		glVertex3f((m_pos.X - 1.0f) + m_dimensions.X, (m_pos.Y - 1.0f), 0); //UVs

		glTexCoord2f(1.0f, 0.0f); //coord for points
		glVertex3f((m_pos.X - 1.0f) + m_dimensions.X, 
			(m_pos.Y - 1.0f) + m_dimensions.Y, 0); //UVs

		glTexCoord2f(0.0f, 0.0f); //coord for points
		glVertex3f((m_pos.X - 1.0f), (m_pos.Y - 1.0f) + m_dimensions.Y, 0); //UVs
		glEnd();
	glDisable(GL_BLEND);
}

void Button::OnMouseButtonDownEvent(const SDL_MouseButtonEvent& mb)
{
	CoordConvert();

	if(mb.type != SDL_MOUSEBUTTONDOWN)
	{
		return;
	}

	//If mouse coord == bounding box of button
 	if  (( ( m_OGLmouseCoord.X >= m_pos.X) 
		&& ( m_OGLmouseCoord.X <= (m_maxPos.X)))
 		&& ((m_OGLmouseCoord.Y >= m_pos.Y) 
		&& ( m_OGLmouseCoord.Y <= (m_maxPos.Y))))
 	{
 		m_isPressed = true;
 	}
}

void Button::OnMouseMotionEvent(const SDL_MouseMotionEvent& mm)
{
	CoordConvert();

	if ( ( ( m_OGLmouseCoord.X >= m_pos.X) 
		&& ( m_OGLmouseCoord.X <= (m_maxPos.X)))
		&& ((m_OGLmouseCoord.Y >= m_pos.Y) 
		&& ( m_OGLmouseCoord.Y <= (m_maxPos.Y))))
	{
		m_isOver = true;
	}
	else
	{
		m_isOver = false;
	}
}

bool Button::WasPressed()
{
	if (!m_active)
	{
		return false;
	}

	bool b = m_isPressed;
	m_isPressed = false;
	return b;
}

const char* Button::GetTypeName()
{
	return "Button";
}

bool Button::Load(File* const f)
{

	return true;
}

GUIObject* CreateNewButton()
{
	return new Button;
}

static bool butt = TheGUIObjectFactory::Instance()->AddToMap("Button", CreateNewButton);